﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace LLCVApi
{
    public class CVAPI
    {
        public delegate int pfCVFunction(int id, int flag, IntPtr data);

        public static pfCVFunction TestM;
        public static pfCVFunction SetDataM;
        public static pfCVFunction GetDataM;
        public static pfCVFunction ProcessM;

        public static IntPtr hSdkDll;
        public static bool Initialize()
        {

            hSdkDll = LoadLibrary("LLCV.dll");
            int a = GetLastError();
            if (hSdkDll == IntPtr.Zero) return false;

            TestM = (pfCVFunction)GetFunctionAddress(hSdkDll, "TestFun", typeof(pfCVFunction));
            SetDataM = (pfCVFunction)GetFunctionAddress(hSdkDll, "SetData", typeof(pfCVFunction));
            GetDataM = (pfCVFunction)GetFunctionAddress(hSdkDll, "GetData", typeof(pfCVFunction));
            ProcessM = (pfCVFunction)GetFunctionAddress(hSdkDll, "Process", typeof(pfCVFunction));

            return true;
        }

        public static int InitCount(int count)
		{
            int[] data_int = new int[4];
            data_int[0] = count;
            IntPtr pdata_int = Marshal.UnsafeAddrOfPinnedArrayElement(data_int, 0);
            return TestM(0, 0, pdata_int);
        }

        public static int CheckAuth()
        {
            int[] data_int = new int[4];
            //data_int[0] = count;
            IntPtr pdata_int = Marshal.UnsafeAddrOfPinnedArrayElement(data_int, 0);
            return TestM(0, 1, pdata_int);
        }
        public static void Uninitialize()
        {
            if (hSdkDll != IntPtr.Zero)
                FreeLibrary(hSdkDll);
            hSdkDll = IntPtr.Zero;
        }

        #region sys dll
        [DllImport("kernel32.dll")]
        static private extern IntPtr LoadLibrary(string lpFileName);
        [DllImport("kernel32.dll")]
        static private extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
        [DllImport("kernel32.dll")]
        static private extern int GetLastError();
        [DllImport("kernel32", EntryPoint = "FreeLibrary", SetLastError = true)]
        static private extern bool FreeLibrary(IntPtr hModule);
        static private Delegate GetFunctionAddress(IntPtr dllModule, string functionName, Type t)
        {
            IntPtr address = GetProcAddress(dllModule, functionName);
            if (address == IntPtr.Zero)
                return null;
            else
                return Marshal.GetDelegateForFunctionPointer(address, t);
        }
        #endregion sys dll
    }
}
